package com.example.teacherservice.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.teacherservice.dto.ChapterCreateRequest;
import com.example.teacherservice.dto.ChapterDTO;
import com.example.teacherservice.dto.CourseUpdateDTO;
import com.example.teacherservice.dto.CreateCourseDTO;
import com.example.teacherservice.entity.Chapter;
import com.example.teacherservice.entity.CouClass;
import com.example.teacherservice.entity.Course;
import com.example.teacherservice.entity.StuCourse;
import com.example.teacherservice.exception.ResourceNotFoundException;
import com.example.teacherservice.repository.*;
import io.micrometer.common.util.StringUtils;
import jakarta.persistence.EntityNotFoundException;
import jakarta.transaction.Transactional;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class CourseService {
    private final CourseRepository courseRepository;
    private final ChapterRepository chapterRepository;
    private final CouClassRepository couClassRepository;
    private final StuCourseRepository stuCourseRepository;
    private final ClassRepository classRepository;
    private final StudentService studentService;
    private final FileStorageService fileStorageService;

    public CourseService(CourseRepository courseRepository, ChapterRepository chapterRepository, CouClassRepository couClassRepository, StuCourseRepository stuCourseRepository, ClassRepository classRepository, StudentService studentService, FileStorageService fileStorageService) {
        this.courseRepository = courseRepository;
        this.chapterRepository = chapterRepository;
        this.couClassRepository = couClassRepository;
        this.stuCourseRepository = stuCourseRepository;
        this.classRepository = classRepository;
        this.studentService = studentService;
        this.fileStorageService = fileStorageService;
    }

    // 新增获取所有课程方法
    public List<Course> getAllCourses() {
        return courseRepository.findAllActiveCourses();
    }

    // 其他已有方法...
    public Course saveCourse(Course course) {
        return courseRepository.save(course);
    }

    public Course updateCourse(Course course) {
        Course existing = courseRepository.findById(course.getId())
                .orElseThrow(() -> new EntityNotFoundException("课程不存在"));

        if(course.getTeaId() == null) {
            course.setTeaId(existing.getTeaId());
        }

        BeanUtils.copyProperties(course, existing, "id", "createTime");
        return courseRepository.save(existing);
    }

    @Transactional
    public void deleteCourse(Long id) {
        // 验证课程是否存在
        Course course = courseRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("课程不存在"));

        // 1. 先删除所有学生课程关联
        stuCourseRepository.deleteByCourseId(id);

        // 2. 删除课程关联的所有班级课程关联
        couClassRepository.deleteByCourseId(id);

        // 3. 删除课程关联的所有章节
        chapterRepository.deleteByCourseId(id);

        // 4. 最后删除课程本身
        courseRepository.deleteById(id);
    }

    public List<Course> getTeacherCourseList(Long teaId) {
        return courseRepository.findByTeaId(teaId);
    }

    public Course getCourseInfo(Long id) {
        return courseRepository.findById(id).orElse(null);
    }

    public Course publishCourse(Long id) {
        Course course = courseRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("Course not found"));
        return courseRepository.save(course);
    }

    /**
     * 根据教师ID获取所有课程
     * @param teaId 教师ID
     * @return 课程列表
     */
    public List<Course> getCoursesByTeacherId(Long teaId) {
        return courseRepository.findByTeaId(teaId);
    }

    @Transactional
    public List<ChapterDTO> addChaptersToCourse(Long courseId, List<ChapterCreateRequest> requests) {
        // 验证课程存在
        if (!courseRepository.existsById(courseId)) {
            throw new ResourceNotFoundException("课程不存在");
        }

        // 使用final包装排序变量
        final int[] currentOrder = {chapterRepository.findMaxSortOrderByCourseId(courseId).orElse(0)};

        List<Chapter> chapters = requests.stream()
                .filter(req -> req.getTitle() != null && !req.getTitle().trim().isEmpty())
                .map(req -> {
                    Chapter chapter = new Chapter();
                    chapter.setCourseId(courseId);
                    chapter.setTitle(req.getTitle());
                    chapter.setUrl(req.getUrl());
                    chapter.setIndex(req.getIndex() != null ? req.getIndex() : 0);
                    chapter.setSortOrder(++currentOrder[0]);
                    chapter.setCreateTime(LocalDateTime.now());
                    chapter.setUpdateTime(LocalDateTime.now());
                    chapter.setDeleted(0);
                    return chapter;
                })
                .collect(Collectors.toList());

        List<Chapter> savedChapters = chapterRepository.saveAll(chapters);
        updateChapterCount(courseId); // 提取的方法

        return savedChapters.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    private void updateChapterCount(Long courseId) {
        courseRepository.findById(courseId).ifPresent(course -> {
            course.setCouCataNum((int)chapterRepository.countByCourseIdAndDeleted(courseId, 0));
            courseRepository.save(course);
        });
    }

    private ChapterDTO convertToDTO(Chapter chapter) {
        return ChapterDTO.builder()
                .id(chapter.getId())
                .courseId(chapter.getCourseId())
                .index(chapter.getIndex())
                .title(chapter.getTitle())
                .url(chapter.getUrl())
                .sortOrder(chapter.getSortOrder())
                .createTime(chapter.getCreateTime())
                .updateTime(chapter.getUpdateTime())
                .build();
    }

    @Transactional
    public Course createCourseWithChapters(CreateCourseDTO dto) {
        // 1. 创建课程基础信息
        Course course = new Course();
        course.setTeaId(dto.getTeaId());
        course.setCouName(dto.getCouName());
        course.setCouIntroduction(dto.getCouIntroduction());
        course.setCouPic(dto.getCouPic());
        course.setCouPrice(dto.getCouPrice());
        Course savedCourse = courseRepository.save(course);

        // 2. 处理章节
        if (CollectionUtils.isNotEmpty(dto.getChapters())) {
            List<Chapter> chapters = new ArrayList<>();

            for (ChapterDTO chapterDto : dto.getChapters()) {
                Chapter chapter = buildChapter(savedCourse.getId(), chapterDto);
                chapters.add(chapter);

                // 打印调试信息
                System.out.printf("章节[%s] URL: %s, 时长: %d秒%n",
                        chapter.getTitle(),
                        chapter.getUrl(),
                        chapter.getDuration());
            }

            chapterRepository.saveAll(chapters);
            savedCourse.setCouCataNum(chapters.size());
        }

        return savedCourse;
    }

    private Chapter buildChapter(Long courseId, ChapterDTO chapterDto) {
        Chapter chapter = new Chapter();
        chapter.setCourseId(courseId);
        chapter.setTitle(chapterDto.getTitle());
        chapter.setUrl(chapterDto.getUrl());
        chapter.setIndex(chapterDto.getIndex());
        chapter.setSortOrder(chapterDto.getIndex()); // 假设index与sortOrder相同

        // 视频时长解析（核心逻辑）
        if (StringUtils.isNotBlank(chapterDto.getUrl())) {
            try {
                // 确保URL以http://或https://开头
                String normalizedUrl = normalizeUrl(chapterDto.getUrl());
                long duration = fileStorageService.parseVideoDuration(normalizedUrl);
                chapter.setDuration(duration);
                System.out.println("✅ 成功解析时长: " + normalizedUrl + " => " + duration + "秒");
            } catch (Exception e) {
                System.out.println("❌ 解析失败: " + chapterDto.getUrl() + ", 原因: " + e.getMessage());
                chapter.setDuration(0L);
            }
        } else {
            chapter.setDuration(0L);
        }

        return chapter;
    }

    // 标准化URL格式
    private String normalizeUrl(String url) {
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            return "http://" + url;
        }
        return url;
    }

    /**
     * 更新课程基本信息（仅名称和简介）
     * @param id 课程ID
     * @param updateDTO 更新数据
     * @return 更新后的课程
     */
    public Course updateCourseInfo(Long id, CourseUpdateDTO updateDTO) {
        Course course = courseRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("课程不存在"));

        // 仅更新允许修改的字段
        if (updateDTO.getCouName() != null) {
            course.setCouName(updateDTO.getCouName());
        }
        if (updateDTO.getCouIntroduction() != null) {
            course.setCouIntroduction(updateDTO.getCouIntroduction());
        }

        return courseRepository.save(course);
    }

    /**
     * 添加课程到班级，并自动为班级所有学生添加该课程
     * @param classId 班级ID
     * @param courseId 课程ID
     * @return 添加结果
     */
    @Transactional
    public boolean addCourseToClass(Long classId, Long courseId) {
        // 1. 验证班级和课程是否存在
        if (!classRepository.existsById(classId)) {
            throw new ResourceNotFoundException("班级不存在");
        }

        if (!courseRepository.existsById(courseId)) {
            throw new ResourceNotFoundException("课程不存在");
        }

        // 2. 检查课程是否已存在于班级
        if (couClassRepository.existsByClassIdAndCourseId(classId, courseId)) {
            throw new IllegalArgumentException("该课程已存在于班级中");
        }

        // 3. 创建班级-课程关联
        CouClass classCourse = new CouClass();
        classCourse.setClassId(classId);
        classCourse.setCourseId(courseId);
        classCourse.setStatus(1); // 1表示正常状态
        couClassRepository.save(classCourse);

        // 4. 为班级所有学生添加该课程
        addCourseToClassStudents(classId, courseId);

        return true;
    }

    /**
     * 为班级所有学生添加课程
     * @param classId 班级ID
     * @param courseId 课程ID
     */
    private void addCourseToClassStudents(Long classId, Long courseId) {
        // 1. 获取班级所有学生ID
        List<Long> studentIds = studentService.getStudentIdsByClassId(classId);

        if (studentIds.isEmpty()) {
            return;
        }

        // 2. 检查哪些学生已经拥有该课程
        List<Long> existingStudentIds = stuCourseRepository.findStudentIdsByCourseIdAndStudentIds(courseId, studentIds);

        // 3. 过滤出需要添加课程的学生
        List<Long> newStudentIds = studentIds.stream()
                .filter(id -> !existingStudentIds.contains(id))
                .collect(Collectors.toList());

        // 4. 批量添加课程
        LocalDateTime now = LocalDateTime.now();
        List<StuCourse> newCourses = newStudentIds.stream()
                .map(studentId -> {
                    StuCourse sc = new StuCourse();
                    sc.setStuId(studentId);
                    sc.setCourseId(courseId);
                    sc.setCreateTime(now);
                    return sc;
                })
                .collect(Collectors.toList());

        stuCourseRepository.saveAll(newCourses);
    }

    /**
     * 从班级移除课程
     * @param classId 班级ID
     * @param courseId 课程ID
     * @return 移除结果
     */
    @Transactional
    public boolean removeCourseFromClass(Long classId, Long courseId) {
        // 1. 验证班级和课程是否存在
        if (!classRepository.existsById(classId)) {
            throw new ResourceNotFoundException("班级不存在");
        }

        if (!courseRepository.existsById(courseId)) {
            throw new ResourceNotFoundException("课程不存在");
        }

        // 2. 检查课程是否存在于班级
        if (!couClassRepository.existsByClassIdAndCourseId(classId, courseId)) {
            throw new IllegalArgumentException("该课程不存在于班级中");
        }

        // 3. 删除班级-课程关联
        couClassRepository.deleteByClassIdAndCourseId(classId, courseId);

        return true;
    }
}